//
// Created by 215609 on 2024/7/2.
//

#include "TsCallJava.h"

TsCallJava::TsCallJava(_JavaVM *mjavaVm, JNIEnv *jniEnv,  jobject jobj)  {
    this->mjavaVm = mjavaVm;
    this->jniEnv = jniEnv;
    this->jobj = jniEnv->NewGlobalRef(jobj);
    jclass  jlz = jniEnv->GetObjectClass(jobj);
    jmid_parpared=jniEnv->GetMethodID(jlz,"onCallParpared","()V");
    jmid_timeinfo=jniEnv->GetMethodID(jlz,"onCallTimeInfo", "(II)V");
}
TsCallJava::~TsCallJava() = default;
void TsCallJava::onCallTimeInfo(int type, int curr, int total) const {
    if (type==MAIN_THREAD){
        jniEnv->CallVoidMethod(jobj,jmid_timeinfo,curr,total);
    }else if (type==CHILD_THREAD){
        JNIEnv *jniEnv;
        if (mjavaVm->AttachCurrentThread(&jniEnv, 0) != JNI_OK) {
            return;
        }
        jniEnv->CallVoidMethod(jobj, jmid_timeinfo, curr, total);
        mjavaVm->DetachCurrentThread();
    }
}

void TsCallJava::onCallParpared(int type) const {
    if (type==MAIN_THREAD){
        jniEnv->CallVoidMethod(jobj,jmid_parpared);
    }else if (type==CHILD_THREAD){
        JNIEnv *jniEnv;
        if (mjavaVm->AttachCurrentThread(&jniEnv,0)!=JNI_OK){
            return;
        }
        jniEnv->CallVoidMethod(jobj,jmid_parpared);
        mjavaVm->DetachCurrentThread();
    }

}